package org.qsoft.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class ActionUtils {

	public static Object convertMap2Object(Map map, Class clz)
			throws Exception {
		try {
			Object obj = clz.newInstance();
			populate(obj, map);

			return obj;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}

	}

	// Map > bean properties
	public static void populate(Object bean, Map properties) throws Exception {

		BeanInfo info = Introspector.getBeanInfo(bean.getClass());

		if (info != null) {
			PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
			for (int i = 0; i < descriptors.length; i++) {
				PropertyDescriptor descriptor = descriptors[i];

				String name = descriptor.getName();
				if (properties.containsKey(name)) {
					Object value = properties.get(name);
					if (value != null) {
						BeanUtils.setProperty(bean, name, value);
					}
				}

			}
		}
	}

	public static void copyProperites(Object source, Object target,
			String[] names) {
		for (int i = 0; i < names.length; i++) {
			try {
				Object value = PropertyUtils.getProperty(source, names[i]);
				PropertyUtils.setProperty(target, names[i], value);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
}
